import { Toast, Dialog } from 'qmp-component'
import { reactive } from 'vue'
import {
  getCustomerContact,
  getMdmCustomerContact,
  saveContacts,
  getNewShopContact
} from '@/apis/ctmCustomerChange/Contact'
import { queryMdmServiceCustDocDefList } from '@/apis/common'
import { validEmail } from '@/utils/validate'
const none: any[] = [null, undefined, '']
interface anyObjectModle {
  [key: string]: any
}
/**
 * 门店联系人必须要有shopCode
 * @param {Number} contactScope  联系人范围（1客户、3门店）
 * @param {Array} otherRequiredKeys 其他必填字段
 */
export function ContactsMixin(contactScope: Number, otherRequiredKeys?: any[], callback?: Function) {
  const defaultData = {
    contactId: '',
    name: '',
    shopBusinessId: '',
    shopName: '',
    contactTypeCode: '',
    contactTypeName: '',
    contactTel: '',
    contactPhone: '',
    contactFax: '',
    email: '',
    address: '',
    isChange: 0,
    isBefore: 0,
    changeType: 'B' // 数据字典：CTM_CHANGE_TYPE (A变更，B新增，C停用)
  }
  const datas = reactive<anyObjectModle>({
    changeCode: '', // 变更单编码
    isNewBusinessTakeover: 0, //是否新商接管:(仅用于新建经销商档案时，门店信息选择是否新商接管的门店联系人)
    shopCode: '', //门店编码
    contactTypes: [],
    list: [], // 当前可操作的数据
    listSource: [] // 原始数据(来源于mdm)
  })
  // 查询联系人列表
  const getList = (isNewShop = false) => {
    const id = `${datas.id}`
    // TODO:查询客户联系人与门店联系人接口变更为两个独立的，待验证。（原调用getCustomerContact，根据变更单Id查询，若存在shopCode则查询新增门店联系人,无shopCode则查询当前变更单下的联系人数据，在新建门店和新建经销商档案的门店联系人中无门店编码shopCode,故暂用getNewShopContact）
    const queryFunction = contactScope === 3 && isNewShop ? getNewShopContact : getCustomerContact
    queryFunction(id, datas.shopCode).then((res: any) => {
      const dots = res.data || []

      const oldList: any[] = dots.filter((v: any) => !none.includes(v.contactId)) //来源于mdm的数据
      const insertList: any[] = dots.filter((v: any) => none.includes(v.contactId)) //新增部分的数据

      /* dots.forEach((e: any) => {
        if (none.includes(e.contactId)) {
          insertList.push(e)
        } else {
          // 去重，若isbefore=1和isbefore=0 都存在，取isbefore=0的数据
          const i = oldList.findIndex((v) => v.contactId === e.contactId)
          if (i > -1) {
            const o = oldList[i]
            if (o.isBefore === 1 && e.isBefore !== 1) {
              oldList[i] = e
            }
          } else {
            oldList.push(e)
          }
        }
      }) */

      datas.list = [...oldList, ...insertList].map((v) => {
        return { ...v, ...{ changeType: v.changeType || '' } }
      })
    })
  }

  // 查询来自MDM的联系人原始数据
  const getMdmContactList = () => {
    getMdmCustomerContact(datas.id, datas.shopCode).then((res: any) => {
      datas.listSource = res.data || []
    })
  }

  // 新增
  const onCreat = () => {
    const obj: any = {
      ...defaultData,
      ...{
        contactId: 'TS' + new Date().getTime(),
        contactScope: contactScope === 3 ? 3 : 1
      }
    }
    datas.list.push(obj)
  }
  // 移除
  const onDelete = (i: number) => {
    const newObj = datas.list[i]
    if (newObj.changeType === 'B' && datas.listSource && datas.listSource.length > 0) {
      datas.listSource.splice(i, 1)
    }
    datas.list.splice(i, 1)
  }
  // 判断是否有填写字段
  const checkEmpty = (list: any[]) => {
    let flag = false
    const requiredKeys: any[] = ['name', 'contactPhone', 'contactTypeCode'].concat(otherRequiredKeys || [])
    if (datas.isNewBusinessTakeover) {
      // 新商接管的，需校验门店名称 shopName,shopBusinessId
      requiredKeys.unshift('shopBusinessId')
    }

    list.forEach((v: any) => {
      for (const [k, val] of Object.entries(v)) {
        if (requiredKeys.includes(k) && none.includes(val)) {
          flag = true
        }
      }
    })
    return flag
  }
  // 校验有效性
  const checkValidity = (list: any[]) => {
    const regPhone = /^1[3456789]\d{9}$/
    const regTel = /^([1]\d{10}|([\(（]?0[0-9]{2,3}[）\)]?[-]?)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?)$/

    const phoneNoPass: any[] = []
    const telNoPass: any[] = []
    const emailNoPass: any[] = []
    list.forEach((v: any, i: number) => {
      if (v.contactTel && !regTel.test(v.contactTel)) {
        telNoPass.push(i + 1)
      }
      if (!regPhone.test(v.contactPhone)) {
        phoneNoPass.push(i + 1)
      }
      if (v.email && !validEmail(v.email)) {
        emailNoPass.push(i + 1)
      }
    })
    if (phoneNoPass.length > 0 || telNoPass.length > 0) {
      let errorMsg = ''
      if (phoneNoPass.length > 0) {
        errorMsg = errorMsg + `<p>联系手机：联系人${phoneNoPass.join(',')}</p>`
      }
      if (telNoPass.length > 0) {
        errorMsg = errorMsg + `<p>联系电话：联系人${telNoPass.join(',')}</p>`
      }
      if (emailNoPass.length > 0) {
        errorMsg = errorMsg + `<p>邮箱：联系人${emailNoPass.join(',')}</p>`
      }
      Dialog.alert({
        title: '以下数据不合规范',
        message: errorMsg,
        allowHtml: true,
        messageAlign: 'left'
      })
      return false
    }
    return true
  }
  // 获取可保存的参数列
  const getListParame = (filter: Boolean) => {
    // const list = !filter ? datas.list : datas.list.filter((v: any) => v.isBefore !== 1)
    const list = datas.list || []
    return list.map((v: any) => {
      const itemData = { ...v }
      if (v.contactId && v.contactId.indexOf('TS') === 0) {
        delete itemData.contactId
        itemData.changeType = 'B'
      }
      itemData.changeCode = datas.changeCode
      itemData.contactScope = contactScope === 3 ? 3 : 1
      if (!none.includes(datas.shopCode)) {
        itemData.shopCode = datas.shopCode
      }
      if (['A', 'C'].includes(itemData.changeType)) {
        itemData.isChange = 1
        itemData.isBefore = 0
      }
      return itemData
    })
  }

  /**
   * 新增保存
   * @param {Boolean} isChange 是否变更
   */
  const onSave = (isChange: any = false) => {
    const list = getListParame(isChange)
    // 校验是否包含未填
    const includeEmpty = checkEmpty(list)
    if (includeEmpty) {
      Toast('请检查必填项是否填写完整')
      return
    }
    // 校验数据有效性
    const isValidty = checkValidity(list)
    if (!isValidty) return

    if (isChange) {
      if (list.length > 0) {
        const noChanges: any[] = [] // 未变更数据的地址
        const tmpChanges = list.filter((v: any) => v.changeType === 'A')
        tmpChanges.forEach((v: any) => {
          const o = datas.listSource.find((e: any) => e.code === v.code)
          const isChange = judgmentChange(o, v)
          if (!isChange) {
            noChanges.push(v.code)
          }
        })
        if (noChanges.length > 0) {
          Dialog.alert({
            title: '联系人未变更',
            message: `编码为：${noChanges.join(',')}的联系人已设变更类型为【变更】，但数据未变更，暂不能保存`,
            allowHtml: true,
            messageAlign: 'left'
          })
          return
        }
      }
    }

    saveContacts(contactScope, datas.changeCode, list).then((res: any) => {
      if (res.success === 1) {
        Toast('保存成功')
        callback && callback()
      }
    })
  }

  // 判断是否存在变更
  const judgmentChange = (source: any, data: any) => {
    let flag = false
    const fields = ['contactTypeCode', 'contactPhone', 'contactTel', 'contactFax', 'email', 'address']
    fields.forEach((k) => {
      const oldValue = source[k]
      const newValue = data[k]
      if ((!none.includes(oldValue) || !none.includes(newValue)) && oldValue !== newValue) {
        flag = true
      }
    })
    return flag
  }

  // 变更类型变更时，判断数据是否有变更
  const onTypeChange = (i: number) => {
    if (datas.listSource.length === 0) return
    const list = [...datas.list]
    const newObj = list[i]
    const sourceObj = datas.listSource.find((v: any) => v.contactId === newObj.contactId)
    if (!sourceObj || !sourceObj.contactId) return
    if (newObj.changeType === 'A') {
      // 变更
      list[i] = { ...newObj, ...{ isBefore: 0 } }
    } else if (newObj.changeType === 'C') {
      // 停用
      list[i] = { ...sourceObj, ...{ isBefore: 0, changeType: 'C' } }
    } else {
      // 不变更
      list[i] = JSON.parse(JSON.stringify(sourceObj))
    }
    datas.list = list
  }

  const initDictData = async () => {
    const types = await queryMdmServiceCustDocDefList('QY019')
    datas.contactTypes = types || []
    /* datas.contactTypes = [
      { dictCode: '1', dictName: '责任人' },
      { dictCode: '2', dictName: '紧急联系人' },
      { dictCode: '3', dictName: '采购联系人' },
      { dictCode: '4', dictName: '运营联系人' },
      { dictCode: '5', dictName: '发货联系人' },
      { dictCode: '6', dictName: '财务联系人' }
    ] */
  }
  return {
    datas,
    getList,
    getMdmContactList,
    onSave,
    onTypeChange,
    onCreat,
    onDelete,
    initDictData
  }
}
